package com.ls.shiroWithJwt.shiro.filter;

import com.ls.shiroWithJwt.constant.Constants;
import com.ls.shiroWithJwt.shiro.token.JwtAuthenticationToken;
import com.ls.shiroWithJwt.utils.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt 过滤器
 */
public class JwtFilter extends AccessControlFilter {


    private static final Logger LOGGER = LoggerFactory.getLogger(AccessControlFilter.class);



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        JwtAuthenticationToken token = createToken((HttpServletRequest) request, response);

        response.setCharacterEncoding("UTF-8");

        if(!StringUtils.hasText(token.getJwt()) && !StringUtils.hasText(token.getUserName())){
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户鉴权信息为空");
            return false;
        }

        if(StringUtils.hasText(token.getJwt())){
            try{
                JwtUtil.verifyToken(token.getJwt());
            }catch (Exception e){
                LOGGER.error("token验证失败:"+e.getMessage());
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "token验证失败");
                return false;
            }
        }

        if (null != getSubject(request, response)
                && getSubject(request, response).isAuthenticated()) {
            return true;
        }

        try {
            Subject subject = getSubject(request, response);
            subject.login(token);
            return true;
        } catch (AuthenticationException e) {
            LOGGER.error(e.getMessage());
            WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return false;
        }
    }

    protected JwtAuthenticationToken createToken(HttpServletRequest request, ServletResponse response) {
        String jwt = request.getHeader(Constants.DEFAULT_JWT_HEADER);
        if(!StringUtils.hasText(jwt)){
            jwt = request.getParameter(Constants.DEFAULT_JWT_URL_TOKEN);
        }
        LOGGER.debug("authenticate jwt token:" + jwt);
        String userName = request.getParameter(Constants.DEFAULT_PRINCIPAL);
        String password = request.getParameter(Constants.DEFAUTL_CREDENTIALS);
        return new JwtAuthenticationToken(jwt, userName, password);
    }
}
